package com.zookeeper.ps;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class DynamicPropertiesHelperFactory {

	private ConfigChangeSubscriber configChangeSubscriber;
	
	private ConcurrentHashMap<String, DynamicPropertiesHelper> helpers = new ConcurrentHashMap<String, DynamicPropertiesHelper>();
	
	public DynamicPropertiesHelperFactory(ConfigChangeSubscriber configChangeSubscriber) {
		this.configChangeSubscriber = configChangeSubscriber;
	}
	
	/**
	 * 获取DynamicPropertiesHelper 如：
	 * @param key
	 * @return
	 */
	public DynamicPropertiesHelper getHelper(String key) {
		DynamicPropertiesHelper helper = (DynamicPropertiesHelper) this.helpers.get(key);
		if (helper != null) {
			return helper;
		}
		return createHelper(key);
	}
	
	/**
	 * 
	 * @param key zk中的一个节点
	 * @return
	 */
	private DynamicPropertiesHelper createHelper(String key) {
		/*
		 * 获取Zookeeper所有的key信息
		 */
		List<String> keys = this.configChangeSubscriber.listKeys();
		if ((keys == null) || (keys.size() == 0)) {
			return null;
		}
		if (!keys.contains(key)) {
			return null;
		}
		/*
		 * 获取节点内容
		 */
		String initValue = this.configChangeSubscriber.readData(key);
		//test=123
		final DynamicPropertiesHelper helper = new DynamicPropertiesHelper(initValue);
		//从Zookeeper 获取该节点内容,并且设置本地的PropertiesHelperMap 上,如果设置成功说明本地已经注册过了，没有重新注册并且订阅Wather事件
		DynamicPropertiesHelper old = (DynamicPropertiesHelper) this.helpers.putIfAbsent(key, helper);
		if (old != null) {
			return old;
		}
		
		/**
		 * 订阅zk数据改变
		 */
		this.configChangeSubscriber.subscribe(key, new ConfigChangeListener() {
			@Override
			public void change(String p1, Object value) {
				//key=======================p1=test.properties  value=test=123
				System.out.println("key=======================p1="+p1+"  value="+value);
				// helper===> DynamicPropertiesHelper_test.properties
				helper.refresh((String) value);
			}
		});
		return helper;
	}
}
